package com.expand.learn.config;

import com.alibaba.fastjson.JSONObject;
import com.expand.learn.annotation.AppResponseBody;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author zhanghaidong
 * @version v1.0
 * @description
 * @date 2020/2/27
 */
@Component
public class CustomizeJsonReturnValueHandler implements HandlerMethodReturnValueHandler {

    /**
     * 该处理程序是否支持给定的方法返回类型(只有返回true才回去调用handleReturnValue)
     * @param returnType
     * @return
     */
    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return returnType.hasMethodAnnotation(AppResponseBody.class);
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        System.out.println("---------handleReturnValue-------" + returnValue.toString());
        mavContainer.setRequestHandled(true);
        HttpServletResponse response= webRequest.getNativeResponse(HttpServletResponse.class);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write(JSONObject.toJSONString(returnValue));
            writer.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
/*
sprig默认的 HandlerMethodReturnValueHandler

0 = {ModelAndViewMethodReturnValueHandler@5503}
1 = {ModelMethodProcessor@5504}
2 = {ViewMethodReturnValueHandler@5505}
3 = {ResponseBodyEmitterReturnValueHandler@5506}
4 = {StreamingResponseBodyReturnValueHandler@5507}
5 = {HttpEntityMethodProcessor@5508}
6 = {HttpHeadersReturnValueHandler@5509}
7 = {CallableMethodReturnValueHandler@5510}
8 = {DeferredResultMethodReturnValueHandler@5511}
9 = {AsyncTaskMethodReturnValueHandler@5512}
10 = {ModelAttributeMethodProcessor@5513}
11 = {RequestResponseBodyMethodProcessor@5514}
12 = {ViewNameMethodReturnValueHandler@5515}
13 = {MapMethodProcessor@5516}
14 = {ModelAttributeMethodProcessor@5518}

 */
